package com.yantong.service.impl;

import com.yantong.config.LocalRedis;
import com.yantong.constant.*;
import com.yantong.enums.MemberStoresApplicationWayEnum;
import com.yantong.enums.OrderPortTypeEnum;
import com.yantong.exception.BDException;
import com.yantong.mapper.*;
import com.yantong.pay.yfz.domain.cust.domain.merchant.response.SpMerchantApplyResponse;
import com.yantong.pay.yfz.pay.YFZSpMerchant;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.BrokerageVo;
import com.yantong.pojo.vo.BusinessTimeVo;
import com.yantong.pojo.vo.CommanerVo;
import com.yantong.pojo.vo.LocalLifeStoreVo;
import com.yantong.result.ResultVo;
import com.yantong.service.*;
import com.yantong.utils.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.yantong.utils.DateUtils.getMonthStart;


/**
 * @author xiangyi
 * @version V1.0.0
 * @Description: 会员服务
 * @date 2018年9月3日 下午6:27:30
 * @since 3.0
 */
@Service
public class MemberServiceImpl implements MemberService {
	private static final Logger logger = LoggerFactory.getLogger(MemberServiceImpl.class);
	private static final String CACHE_TICKET_NAME = "member_ticket";
	private static final String CACHE_NAME = "member";

	@Autowired
	private MemberMapper memberMapper;

	@Autowired
	private PaymentMapper paymentMapper;

	@Autowired
	private BalanceService balanceService;

	@Autowired
	private ConfigService configService;

	@Autowired
	private CommissionService commissionService;

	@Autowired
	private OrderMapper orderMapper;

	@Autowired
	private LocalRedis localRedis;

	@Autowired
	@Lazy
	private OrderService orderService;
	@Autowired
	private UserService userService;
	@Autowired
	private CentreIndustryMapper centreIndustryMapper;
	@Autowired
	private WxNotifyService wxNotifyService;
	@Autowired
	private CentreService centreService;

	@Autowired
	private BondFlowMapper bondFlowMapper;

	@Autowired
	@Lazy
	private MemberWalletService memberWalletService;

	@Autowired
	private CentreAmountMapper centreAmountMapper;

	@Autowired
	private TBusinessCardService tBusinessCardService;

	@Autowired
	private TBusinessCardMapper tBusinessCardMapper;

	@Autowired
	private AmountLogMapper amountLogMapper;

	@Autowired
	private YFZSpMerchant yfzSpMerchant;
	@Autowired
	private CentreTerminalMapper centreTerminalMapper;
	@Autowired
	private StoreService storeService;
	@Autowired
	private OrderProductMapper orderProductMapper;
	@Autowired
	private MemberAggregationMapper memberAggregationMapper;
	@Autowired
	private FansMapper fansMapper;



	@Value("${Applet.TemplatemsgCreateUserUrl}")
	private String templatemsgCreateUserUrl;




	@Override
//    @Cacheable(value = CACHE_NAME, keyGenerator = "localKeyGenerator")
	public Member getByKey(Long id) {
		logger.info("获取会员信息，mid:{}", id);
		if (id == null) {
			return null;
		}
		Member member = memberMapper.selectByPrimaryKey(id);
		if (member == null) {
			return null;
		}
		logger.info("获取会员信息成功，id:{},centreid:{}", member.getId(),member.getCentreId());
		member.setTicket(null);
		return member;
	}




	@Override
	public List<Member> listCenterTeamList(Long centerId) {
		return memberMapper.getTeamListByCenterId(centerId);
	}



	@Override
	public List<Member> listCenterList(Long centerId) {
		return memberMapper.getListByCenterId(centerId);
	}

	@Override
	public List<Member> getAllMember(Map params) {
		List<Member> list = memberMapper.getListByWhere(params);
		if (null == list) {
			list = new ArrayList<>();
		}
		return list;
	}

	@Override
	public Member login(String mobile, String encPassword, Long centerId) {
		return memberMapper.getByMobilePwd(mobile, encPassword, centerId);
	}



	@Override
	public CommanerVo getCommanderByMembId(Long memberId) {
		return memberMapper.getCommanderByMembId(memberId);
	}

	@Override
	public Member getTmByKey(Long tmid) {
		if (tmid == null) {
			return null;
		}
		return memberMapper.selectByPrimaryKey(tmid);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int cancelCommanderUpdate(Member member) {
		if (member == null || member.getId() == null) {
			return 0;
		}
		Member m = memberMapper.selectByPrimaryKey(member.getId());

		//寻找当前门店的所有下级
		List<Member> list = getSubordinate(member.getId());
		int flag = 0;
		//本门店有上级的情况下, 将本门店的上级赋给本门店的所有下级的上级
		if (m.getUpTeamid() != null) {
			if (list != null && list.size() > 0) {
				for (Member mem : list) {
					mem.setUpTeamid(m.getUpTeamid());
					mem.setUpTeamname(m.getUpTeamname());
					int n = memberMapper.updateByUpTeamid(mem);
					if (n > 0) {
						flag++;
					}
				}
			}
		} else {//本门店无上级的情况下, 将本门店的所有下级的上级赋空值
			if (list != null && list.size() > 0) {
				for (Member mem : list) {
					mem.setUpTeamid(null);
					mem.setUpTeamname("");
					int n = memberMapper.updateByUpTeamid(mem);
					if (n > 0) {
						flag++;
					}
				}
			}
		}
		int in = memberMapper.updateByPrimaryKeySelective(member);
		if (in > 0) {
			flag++;
		}

		//取消门店的所有店员
		memberMapper.updateClerkByTeamid(m);

		return flag;
	}


	@Override
	public List<Member> getSubordinate(Long upTeamid) {
		List<Member> list = memberMapper.getSubordinate(upTeamid);
		if (list != null && list.size() > 0) {
			return list;
		}
		return null;
	}

	@Override
	public Member getDetail(Long mid) {
		if (mid == null) {
			return null;
		}
		Member member = memberMapper.selectByPrimaryKey(mid);
		if (member == null) {
			return null;
		}
		OrderExample orderExample = new OrderExample();
		OrderExample.Criteria criteria = orderExample.createCriteria();
		criteria.andMidEqualTo(mid);
		Integer orderSum = orderMapper.countByExample(orderExample);
		member.setOrderSum(orderSum);
		BigDecimal paypriceSum = orderMapper.paypriceSum(orderExample);
		if (paypriceSum != null) {
			member.setPaypriceSum(paypriceSum);
		} else {
			member.setPaypriceSum(new BigDecimal("0.00"));
		}
		member.setTicket(null);
		member.setWaitGrantCommission(commissionService.commissionCount(mid, 0));

		return member;
	}


	@Override
//    @CacheEvict(value = CACHE_NAME, allEntries = true)
	public int updateMember(Member member) {
		if (member == null || member.getId() == null) {
			return 0;
		}
		HashMap<String, Object> params = new HashMap<>(2);
		if (member.getId() != null) {
			params.put("mid", member.getId());
			Member memberReal = memberMapper.selectByPrimaryKey(member.getId());
			//如果修改的会员信息是店员，则将缓存中的二维码删除，重新生成
			if (null != memberReal && member.getIsClerk() != null && member.getIsClerk() == 1) {
				localRedis.delByKey("inviteqrurl3" + member.getId());
				//设置默认密码123456
				member.setPwd(DigestUtils.sha256Hex(SystemConstant.DEFAULT_PWD_MEMBER.getConstants()));
			}
		}
		if (member.getCentreId() != null) {
			params.put("centreId", member.getCentreId());
		}
		List<Member> list = memberMapper.getTeamUnderMeberById(params);
		if (list != null && list.size() > 0) {
			params.put("list", list);
			memberMapper.updateMeberById(params);
		}
		return memberMapper.updateByPrimaryKeySelective(member);
	}

	@Override
	public ResultVo noCheckUpdate(Member member) {
		if (member == null || member.getId() == null) {
			return ResultVo.error();
		}
		Member memberAll = this.getByKey(member.getId());
		if (PayStatus.PAY_SUCCESS.getCode() != member.getPayStatus()) {
			throw new BDException("请支付！");
		}
		//-------↓↓↓↓↓↓↓↓审核通过将自己设置为上次购买门店↓↓↓↓↓↓↓↓↓--------
		String name = "";
		if (!StringUtils.isEmpty(member.getRealname())) {
			name = member.getRealname();
		} else {
			if (!StringUtils.isEmpty(member.getNickname())) {
				name = member.getNickname();
			}
		}
		member.setUpshopTid(member.getId());
		member.setUpshopName(name);
		member.setTeamid(member.getId());
		//-------↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑--------
		if (StringUtils.isEmpty(member.getLat())) {
			member.setLng(null);
			member.setLat(null);
		} else {
			String[] str = member.getLat().split(",");
			if (str != null && str.length >= 2) {
				member.setLng(str[0]);
				member.setLat(str[1]);
			} else {
				member.setLng(null);
				member.setLat(null);
			}
		}

		//用户电话号码+centerId作为系统管理员用户名，用户注册的时候，已经保存了的
		String adminName = member.getAdminUser();
		if (ValidateUtil.isEmptyString(adminName)) {
			adminName = member.getMobile() + member.getCentreId();
			member.setAdminUser(adminName);
		}
		if (this.updateMember(member) < 1) {
			return ResultVo.error();
		}else{
			logger.info("门店自动审核完成！===========");
		}
		//生成后台门店管理账号
		if (!userService.checkExit(adminName)) {
			SysUser user = new SysUser();
			user.setName(adminName);
			user.setNickname(name);
			user.setPassword(SystemConstant.DEFAULT_PWD_USER.getConstants());
			user.setPhone(member.getMobile());
			user.setCentreId(member.getCentreId());
			user.setFlag(PermisFlag.FLAG_SHOP);
			user.setTeamId(member.getId());

			Centre centre = centreService.getCentreById(member.getCentreId());

			String roleId = SystemConstant.USER_ID_SHOP_ADMIN.getConstants();
			if (MemberStoresApplicationWayEnum.LOCAL_LIFE.getCode().equals(memberAll.getStoresApplicationWay())) {
				roleId = SystemConstant.USER_ID_SHOP_LOCAL_ADMIN.getConstants();
			} else {
				//小程序申请的门店需要查询对应行业的角色id
				if (centre != null && centre.getIndustryId() != null) {
					CentreIndustry centreIndustry = centreIndustryMapper.selectByPrimaryKey(Long.valueOf(centre.getIndustryId()));
					if (centreIndustry != null && centreIndustry.getStoreRoleId() != null) {
						roleId = centreIndustry.getStoreRoleId().toString();
					}
				}
			}

			//门店
			userService.saveUser(user, roleId);
		} else {
			SysUser user = userService.getUserByName(adminName);
			Centre centre = centreService.getCentreById(member.getCentreId());
			String roleId = SystemConstant.USER_ID_SHOP_ADMIN.getConstants();
			if (MemberStoresApplicationWayEnum.LOCAL_LIFE.getCode().equals(memberAll.getStoresApplicationWay())) {
				roleId = SystemConstant.USER_ID_SHOP_LOCAL_ADMIN.getConstants();
			} else {
				//小程序申请的门店需要查询对应行业的角色id
				if (centre != null && centre.getIndustryId() != null) {
					CentreIndustry centreIndustry = centreIndustryMapper.selectByPrimaryKey(Long.valueOf(centre.getIndustryId()));
					if (centreIndustry != null && centreIndustry.getStoreRoleId() != null) {
						roleId = centreIndustry.getStoreRoleId().toString();
					}
				}
			}
			//修改所属门店
			user.setTeamId(member.getId());
			List<Long> list = new ArrayList<>();
			list.add(Long.valueOf(roleId));
			user.setRoleIds(list);
			userService.updateUser(user);
		}

		//是否商户下直属门店(0不是1是)
		Integer isMerchantDirectStore = memberAll.getIsMerchantDirectStore();
		if(isMerchantDirectStore != null && isMerchantDirectStore == 0 ){
			String merchantName = memberAll.getMerchantName();
			String lawyerCertNo = memberAll.getLawyerCertNo();
			String contactPhone = memberAll.getContactPhone();
			String email = memberAll.getMerchantEmail();
			String settleAccountNo = memberAll.getSettleAccountNo();
			String openBank = memberAll.getOpenBank();
			SpMerchantApplyResponse spMerchantApplyResponse = null;
			try {
				Centre centre = centreService.getByKey(member.getCentreId());

				spMerchantApplyResponse = yfzSpMerchant.apply2(centre.getYplCustomerCode(), merchantName, lawyerCertNo, contactPhone, email, settleAccountNo, openBank);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (!"0000".equals(spMerchantApplyResponse.getRespCode())) {
				//改为审核不通过
				Member newMember = new Member();
				newMember.setId(member.getId());
				newMember.setIsteam(4);
				this.updateByPrimaryKeySelective(newMember);
				throw new BDException(spMerchantApplyResponse.getRespMsg()+"请联系管理员！",500);
			}
			if (ValidateUtil.isNotEmptyString(spMerchantApplyResponse.getAcqMerId())) {
				this.updateMemberAsync(member);
			}

		}

		// 发送短信
		try {
			//通知用户
			String msgContent = "您的后台管理帐号为：" + adminName + "，密码为：" + SystemConstant.DEFAULT_PWD_USER.getConstants() + "，欢迎您的加入！";
			//shiYuanSmsClient.send(member.getMobile(), msgContent);

			String newTemplatemsgCreateUserUrl = templatemsgCreateUserUrl + "?centerId=" + member.getCentreId();
			msgContent = msgContent + "后台管理系统入口：" +newTemplatemsgCreateUserUrl;

			Map<String, String> map = new HashMap<>();
			map.put("url", newTemplatemsgCreateUserUrl);
			map.put("accounts", adminName);
			map.put("accountsStr", "用户名：" + adminName);
			map.put("pwdStr", "您的密码为" + SystemConstant.DEFAULT_PWD_USER.getConstants());
			map.put("pwd", SystemConstant.DEFAULT_PWD_USER.getConstants());
			map.put("type", "门店【" + member.gettXiaoqu() + "】后台管理帐号创建");
			map.put("createdDate", DateUtil.convertDateToStr(new Date(), DateUtil.yyyy_MM_dd_HH_mm_ss));
			map.put("type0", "门店【" + member.gettXiaoqu() + "】后台管理帐号创建成功");
			String str = "";
			str += "用户名: " + adminName + ",\n";
			str += "用户密码: " + SystemConstant.DEFAULT_PWD_USER.getConstants() + ",\n";
			map.put("remark", str);
			map.put("status", "创建成功,已启用!");
			//发送模版消息
			orderService.sendAccountsTemplateToUser(member.getCentreId(), member.getId(), map);

			//发送公众号文本消息
			if (ValidateUtil.isNotEmptyString(member.getOpenid())) {
				//消息通知
				WxNotifyParam notifyParam = new WxNotifyParam();
				notifyParam.setMessageType(WxMessageType.MESSAGE_TYPE_TEXT.getType());//文本消息
				notifyParam.setCenterId(member.getCentreId());
				notifyParam.setGzhOpenId(member.getOpenid());
				notifyParam.setTeminal(WxTerminal.TERMINAL_GZH.getTerminal());
				notifyParam.setContent(msgContent);
				wxNotifyService.sendNotify(notifyParam);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResultVo.ok();
	}


	@Async
	@CacheEvict(value = CACHE_NAME, allEntries = true)
	public void updateMemberAsync(Member member) {
		if (member == null || member.getId() == null) {
			return;
		}
		logger.info("异步更新会员信息...");
		memberMapper.updateByPrimaryKeySelective(member);
	}

	@Override
	public PageUtils<Member> queryList(String queryItem, Long centreId, int offset, int limit, Integer isteam) {
		PageUtils<Member> pageUtils = new PageUtils<>();

		HashMap<String, Object> params = new HashMap<>(2);
		if (StringUtils.isNotEmpty(queryItem)) {
			params.put("queryItem", queryItem);
		}
		if (centreId != null) {
			params.put("centreId", centreId);
		}
		if (isteam != null) {
			params.put("isteam", isteam);
			if (StringUtils.isNotEmpty(queryItem)) {
				params.put("queryItem", null);
				params.put("queryTeamItem", queryItem);
			}
		}
		int total = memberMapper.getCountByWhere(params);
		if (total > 0) {
			List<Member> list = memberMapper.getListByWhere(params, new RowBounds(offset, limit));
			list.forEach(m -> m.setTicket(null));
			pageUtils.setRows(list);
			pageUtils.setTotal(total);
		}
		return pageUtils;
	}

	@Override
	public PageUtils<Member> listMembers(ListMemberParams listMemberParams, Member member, int offset, int limit) {
		logger.info("list members, listMemberParams:{}, member:{}, offset:{}, limit:{}", listMemberParams, member, offset, limit);
		PageUtils<Member> pageUtils = new PageUtils<>();
		HashMap<String, Object> searchMap = new HashMap<>(8);
        /*if (StringUtils.isNotEmpty(listMemberParams.getFollow())) {
            searchMap.put("follow", Integer.parseInt(listMemberParams.getFollow()));
        }*/
		if (StringUtils.isNotEmpty(listMemberParams.getStartDate())) {
			searchMap.put("startDate", listMemberParams.getStartDate() + " 00:00:00");
		}
		if (StringUtils.isNotEmpty(listMemberParams.getEndDate())) {
			searchMap.put("endDate", listMemberParams.getEndDate() + " 23:59:59");
		}
		if (StringUtils.isNotEmpty(member.getNickname())) {
			searchMap.put("nickname", member.getNickname());
		}
		if (StringUtils.isNotEmpty(member.getMobile())) {
			searchMap.put("mobile", member.getMobile());
		}
		if (StringUtils.isNotEmpty(listMemberParams.getKeyword())) {
			searchMap.put("keyword", listMemberParams.getKeyword());
		}
		if (member.getId() != null) {
			searchMap.put("id", member.getId());
		}
		if (listMemberParams.getCentreId() != null) {
			searchMap.put("centreId", listMemberParams.getCentreId());
		}
		if (listMemberParams.getLiansuoId() != null) {
			searchMap.put("teamid", listMemberParams.getLiansuoId());
		}
		if (listMemberParams.getIsUserAgent() != null) {
			searchMap.put("isUserAgent", listMemberParams.getIsUserAgent());
		}
		if (listMemberParams.getIsClerk() != null) {
			searchMap.put("isClerk", listMemberParams.getIsClerk());
		}
		if (listMemberParams.getIsAnchor() != null) {
			searchMap.put("isAnchor", listMemberParams.getIsAnchor());
		}
		if (listMemberParams.getIsActive() != null) {
			searchMap.put("isActive", listMemberParams.getIsActive());
		}

		int[] isteams = {MemberType.NORMAL.getCode(), MemberType.INVITE_TO_COMMANDER.getCode(), MemberType.APPLY_TO_COMMANDER.getCode(), MemberType.COMMANDER.getCode(), MemberType.CHECKED_NO_OPEN.getCode()};
		searchMap.put("isteams", isteams);
		searchMap.put("ORDERLIST", "t.createtime desc");
		int total = memberMapper.getCountByWhere(searchMap);
		if (total > 0) {
			logger.info("list members, total size:{}", total);
			pageUtils.setTotal(total);
			List<Member> memberList = memberMapper.getListByWhere(searchMap, new RowBounds(offset, limit));
			if (memberList != null && memberList.size() > 0) {
				memberList.forEach((e) -> e.setTicket(null));
			}
			pageUtils.setRows(memberList);
		} else {
			logger.info("list members not found");
			pageUtils.setRows(new ArrayList<>());
		}
		return pageUtils;
	}


	/**
	 * 得到门店下面的用户
	 *
	 * @return
	 */
	public PageUtils<Member> getTeamtheUserByMid(Long mid, int offset, int limit) {
		PageUtils<Member> pageUtils = new PageUtils<Member>();
		Map<String, Object> params = new HashMap<String, Object>();
		if (mid != null) {
			params.put("mid", mid);
		}
		int total = memberMapper.countTotal(params);
		if (total > 0) {
			pageUtils.setTotal(total);
			pageUtils.setRows(memberMapper.getTeamtheUserByMid(params, new RowBounds(offset, limit)));
		}
		return pageUtils;
	}

	/**
	 * 得到门店下面的用户
	 *
	 * @return
	 */
	public List<Member> getTeamtheUserByMid(Long mid) {
		Map<String, Object> params = new HashMap<String, Object>();
		if (mid != null) {
			params.put("mid", mid);
		}
		return memberMapper.getTeamtheUserByMid(params);
	}



	@Override
	@Transactional(rollbackFor = Exception.class)
	public int updateMemberAndBondFlow(Member member, BondFlow bondFlow, int flag) {
		if (member == null || member.getId() == null) {
			return 0;
		}
		Member mem = memberMapper.selectByPrimaryKey(member.getId());
		String name = "";
		if (StringUtils.isNotEmpty(mem.getRealname())) {
			name = mem.getRealname();
		} else {
			if (StringUtils.isNotEmpty(mem.getNickname())) {
				name = mem.getNickname();
			}
		}
		if (flag == 0) {
			BondFlow record = new BondFlow();
			record.setMid(mem.getId());
			record.setUsername(name);
			record.setpMoney(new BigDecimal(0));
			record.setMoney(member.getBondmoney());
			record.setfMoney(member.getBondmoney());
			record.setType(0);
			record.setCreateTime(new Date());
			record.setContent("初始设置");
			record.setCentreId(mem.getCentreId());
			int updateBondFlow = bondFlowMapper.insertSelective(record);
			if (updateBondFlow > 0) {
				return memberMapper.updateByPrimaryKeySelective(member);
			} else {
				return 0;
			}
		}
		if (bondFlow != null && flag == 1) {
			bondFlow.setId(null);
			bondFlow.setMid(mem.getId());
			bondFlow.setUsername(name);
			BigDecimal bondmoney = mem.getBondmoney() != null ? mem.getBondmoney() : new BigDecimal(0);//申请前金额
			bondFlow.setpMoney(bondmoney);
			BigDecimal money = bondFlow.getMoney() != null ? bondFlow.getMoney() : new BigDecimal(0);//申请金额
			if (bondFlow.getType() == 0) {
				bondFlow.setType(0);
				bondFlow.setfMoney(bondmoney.add(money));//申请后金额
			}
			if (bondFlow.getType() == 1) {
				bondFlow.setType(1);
				bondFlow.setfMoney(bondmoney.subtract(money));//申请后金额
			}

			bondFlow.setCreateTime(new Date());
			bondFlow.setCentreId(mem.getCentreId());
			int updateBondFlow = bondFlowMapper.insertSelective(bondFlow);
			if (updateBondFlow > 0) {
				member.setBondmoney(bondFlow.getfMoney());
				return memberMapper.updateByPrimaryKeySelective(member);
			} else {
				return 0;
			}
		}
		return 0;
	}


	@Override
	public PageUtils<Member> queryComList(String queryItem, Long centreId, int offset, int limit) {
		PageUtils<Member> pageUtils = new PageUtils<>();
		HashMap<String, Object> params = new HashMap<>(2);
		if (StringUtils.isNotEmpty(queryItem)) {
			params.put("queryItem", queryItem);
		}
		if (centreId != null) {
			params.put("centreId", centreId);
		}
		params.put("isteam", MemberType.COMMANDER.getCode());
		int total = memberMapper.getCountByWhere2(params);
		if (total > 0) {
			pageUtils.setRows(memberMapper.getListByWhere2(params, new RowBounds(offset, limit)));
			pageUtils.setTotal(total);
		}
		return pageUtils;
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public int changeMemberAndWallet(Member member, MemberWalletLog memberWalletLog) {
		if (member == null || member.getId() == null) {
			return 0;
		}
		//给用户添加资产
		Member memberParam = getByKey(member.getId());
		MemberWallet memberWallet = memberWalletService.findById(memberParam);

		if (memberWallet != null ) {
			memberWalletLog.setEADD(memberWallet.getEADD());
			memberWalletLog.setType(1);
			memberWalletLog.setMemberId(member.getId());
			if (memberWalletLog.getOperationType().equals(1)){
				memberWallet.setAA(memberWallet.getAA().add(memberWalletLog.getAssetCount()));
			}else if (memberWalletLog.getOperationType().equals(2)){
				if(memberWalletLog.getAssetCount().compareTo(memberWallet.getAA()) > -1){
					throw new BDException("转出资产不足!");
				}
				memberWallet.setAA(memberWallet.getAA().subtract(memberWalletLog.getAssetCount()));
			}else {
				return 0;
			}
			memberWalletService.update(memberWallet);
			//添加资产转入记录
			memberWalletService.insertLog(memberWalletLog);
			return 1;
		}else {
			throw new BDException("该会员没有资产记录!");
		}
	}

	/**
	 * 获取会员列表数据  没有分页
	 *
	 * @param listMemberParams
	 * @param member
	 * @return
	 */
	@Override
	public List<Member> epListMembers(ListMemberParams listMemberParams, Member member) {
		HashMap<String, Object> searchMap = new HashMap<>(8);
          /*if (StringUtils.isNotEmpty(listMemberParams.getFollow())) {
              searchMap.put("follow", Integer.parseInt(listMemberParams.getFollow()));
          }*/
		if (StringUtils.isNotEmpty(listMemberParams.getStartDate())) {
			searchMap.put("startDate", listMemberParams.getStartDate() + " 00:00:00");
		}
		if (StringUtils.isNotEmpty(listMemberParams.getEndDate())) {
			searchMap.put("endDate", listMemberParams.getEndDate() + " 23:59:59");
		}
		if (StringUtils.isNotEmpty(member.getNickname())) {
			searchMap.put("nickname", member.getNickname());
		}
		if (StringUtils.isNotEmpty(member.getMobile())) {
			searchMap.put("mobile", member.getMobile());
		}
		if (StringUtils.isNotEmpty(listMemberParams.getKeyword())) {
			searchMap.put("keyword", listMemberParams.getKeyword());
		}
		if (member.getId() != null) {
			searchMap.put("id", member.getId());
		}
		if (listMemberParams.getCentreId() != null) {
			searchMap.put("centreId", listMemberParams.getCentreId());
		}

		int[] isteams = {MemberType.NORMAL.getCode(), MemberType.INVITE_TO_COMMANDER.getCode(), MemberType.APPLY_TO_COMMANDER.getCode(), MemberType.CHECKED_NO_OPEN.getCode()};
		searchMap.put("isteams", isteams);
		searchMap.put("ORDERLIST", "t.createtime desc");
		int total = memberMapper.getCountByWhere(searchMap);
		if (total > 0) {
			logger.info("list members, total size:{}", total);
			List<Member> memberList = memberMapper.getListByWhere(searchMap);
			if (memberList != null && memberList.size() > 0) {
				memberList.forEach((e) -> e.setTicket(null));
			}
			return memberList;
		} else {
			logger.info("list members not found");
			return new ArrayList<>();
		}
	}

	@Override
	public int updatePassword(UpdatePasswordReq updatePasswordReq) {
		Member member = new Member();
		member.setId(updatePasswordReq.getId());
		member.setPwd(DigestUtils.sha256Hex(updatePasswordReq.getPassword()));
		return memberMapper.updateByPrimaryKeySelective(member);
	}

	@Override
	@CacheEvict(value = CACHE_NAME, allEntries = true)
	@Transactional(rollbackFor = Exception.class)
	public int updateMeberVipAndCommission(Long mid) {
		if (mid == null) {
			return 0;
		}
		Member member = memberMapper.selectByPrimaryKey(mid);
		if (member == null) {
			logger.info("not found member info by id:{}", mid);
			return 0;
		}
		//vip商户数据集合
		List<String> strlist = Arrays.asList(member.getVipofcentreId().split("-"));
//        if (member.getIsVip() == 1 && strlist.indexOf(member.getCentreId().toString()) != -1) {
//            throw new BDException(BusinessCode.MEMBER_VIP_ALREADY);
//        }
		TradeConfig tc = configService.getTradeConfig(member.getCentreId());
		if (tc == null || tc.getVipPrice() == null) {
			throw new BDException(BusinessCode.MEMBER_VIP_PRICE_ERROR);
		}
		member.setVipofcentreId(member.getVipofcentreId().concat(member.getCentreId() + "-"));
//        member.setIsVip(1);
		member.setVipTime(new Date());

		Payment payment = new Payment();
		payment.setCreateTime(new Date());
		payment.setMid(mid);
		payment.setMoney(BigDecimal.valueOf(tc.getVipPrice()));
		payment.setStatus(2);
		payment.setType("2");
		payment.setStyle(3);
		payment.setOpenid(member.getOpenid());
		paymentMapper.insertSelective(payment);

		//站点余额账号
		CentreAmount ca = centreAmountMapper.getByKey(member.getCentreId());
		AmountLog al = new AmountLog();
		al.setCentreId(member.getCentreId());
		al.setBeforeamount(ca.getAmount());
		al.setMoney(new BigDecimal(tc.getVipPrice()));
		al.setAfteramount(ca.getAmount().add(new BigDecimal(tc.getVipPrice())));
		al.setCreateTime(new Date());
		al.setFlowType(13);
		al.setProductType(1);
		al.setRemark("会员购买vip");

		//电子名片的分佣逻辑


		if (member.getGrade() == 1) {//只有是普通会员才去升级
			member.setGrade(2);
			memberMapper.updateByPrimaryKeySelective(member);
		}


		Long refId = member.getUserid();
		if (refId != null) {
			Member refMem = memberMapper.selectByPrimaryKey(refId);
			//获取推荐人推荐用户的个数
			Member tjrMem = refMem;
			while (tjrMem != null) {
				int grade = tjrMem.getGrade();
				int count = getCountByMemberByMidBuy(tjrMem.getId());
				//VI的级别配置
				BrokerageVo brokerageVov1 = tBusinessCardService.getBrokerageById(3L);
				if (count >= brokerageVov1.getCount().intValue()) {
					tjrMem.setGrade(brokerageVov1.getId().intValue());
				}
				BrokerageVo brokerageVov2 = tBusinessCardService.getBrokerageById(4L);
				if (count >= brokerageVov2.getCount().intValue()) {
					tjrMem.setGrade(brokerageVov2.getId().intValue());
				}
				BrokerageVo brokerageVov3 = tBusinessCardService.getBrokerageById(5L);
				if (count >= brokerageVov3.getCount().intValue()) {
					tjrMem.setGrade(brokerageVov3.getId().intValue());
				}

				if (tjrMem.getGrade() > grade) {//如果是升级了才会去改变用户会员等级
					memberMapper.updateByPrimaryKey(tjrMem);
				}

				tjrMem = getByKey(tjrMem.getUserid());
			}

			if (refMem != null && refMem.getGrade() >= 2) {
				int grade = refMem.getGrade();
				BrokerageVo brokerage = tBusinessCardService.getBrokerageById((long) grade);

				BigDecimal commission1 = BigDecimal.ZERO; //直推佣金
				BigDecimal commission2 = BigDecimal.ZERO; //团队佣金
				//                 if ("188".equals(level)) {
				commission1 = brokerage.getBrokerage1();
				if (grade > 2) {//团队佣金
					commission2 = brokerage.getBrokerage2();
				}
				//                  }

				//设置会员推荐佣金=直推佣金+团队佣金
				refMem.setCredit2(refMem.getCredit2().add(commission1).add(commission2));
				//推荐佣金记录
				CommissionLog log1 = new CommissionLog();
				log1.setMid(refId);
				log1.setType(1);
				log1.setCommission(commission1);
				log1.setIsGrant(1);
				//保存数据
				tBusinessCardMapper.insertCommission(log1);
				if (grade > 2) {//团队佣金必须是v1或者以上
					//团队佣金记录
					CommissionLog log2 = new CommissionLog();
					log2.setMid(refId);
					log2.setType(2);
					log2.setCommission(commission2);
					log2.setIsGrant(1);
					tBusinessCardMapper.insertCommission(log2);
				}
				memberMapper.updateByPrimaryKeySelective(refMem);

				//团队管理佣金
				int gradeNow = refMem.getGrade();
				//二级推荐人佣金
				Member member1 = memberMapper.selectByPrimaryKey(refMem.getUserid());
				while (member1 != null) {
					if (member1 != null) {
						int memGrade = member1.getGrade();
						if (memGrade > gradeNow && memGrade > 2) {
							gradeNow = memGrade;
							BrokerageVo brokerage1 = tBusinessCardService.getBrokerageById((long) gradeNow);
							BigDecimal commission3 = brokerage1.getBrokerage2();
							CommissionLog log3 = new CommissionLog();
							log3.setMid(member1.getId());
							log3.setType(2);
							log3.setCommission(commission3);
							log3.setIsGrant(1);
							tBusinessCardMapper.insertCommission(log3);
							member1.setCredit2(member1.getCredit2().add(commission3));
							memberMapper.updateByPrimaryKeySelective(member1);

							member1 = memberMapper.selectByPrimaryKey(member1.getUserid());
						} else {
							member1 = memberMapper.selectByPrimaryKey(member1.getUserid());
						}
					} else {
						break;
					}
				}

			}
		}

		//站点流水记录
		amountLogMapper.saveAmountLog(al);
		centreAmountMapper.changeAmount(new CentreAmount(member.getCentreId(), BigDecimal.valueOf(tc.getVipPrice())));
		return memberMapper.updateByPrimaryKeySelective(member);
	}

	//获取团队成员个数
	public int getCountByMemberByMidBuy(Long id) {
		String str = memberMapper.getCountByMemberByMidBuy(id);
		if (str == null) {
			return 0;
		} else {
			String arr[] = str.split(",");
			return arr.length - 1;
		}
	}

	@Override
	public boolean commissionFlag(Member member,Integer type) {
		boolean flag = false;
		if(member == null){
			return flag;
		}
		if(OrderPortTypeEnum.LIFE.getCode() == type){
			//本地生活得有vip才分佣
			if (member.getIsVip() == 1) {
				flag = true;
			}
		}else{
			flag = true;
		}
		return flag;
	}

	@Override
	public PageUtils<Member> listAllShops(Map<String, Object> param) {
		PageUtils<Member> shopPageUtils = new PageUtils<>();
		shopPageUtils.setRows(memberMapper.pageListBycondition(param, new RowBounds(
				Integer.parseInt(param.get("offset").toString()), Integer.parseInt(param.get("limit").toString()))));
		int total = memberMapper.queryTotal(param);
		shopPageUtils.setTotal(total);
		return shopPageUtils;
	}

	@Override
	public int registTeam(Member member) {
		if (member == null || member.getId() == null) {
			return 0;
		}
		member.setsTime(new Date());
		member.setIsteam(MemberType.APPLY_TO_COMMANDER.getCode());
		member.setPayStatus(PayStatus.NO_PAY.getCode());
		member.setPwd(DigestUtils.sha256Hex(SystemConstant.DEFAULT_PWD_MEMBER.getConstants()));
		Centre centre = centreService.getCentreById(member.getCentreId());
		if (centre != null && ValidateUtil.isNotEmptyString(centre.getIndustryId())) {
			member.setIndustryId(Long.parseLong(centre.getIndustryId()));
		}
		//查询门店申请需要的费用
		BigDecimal payPrice = BigDecimal.ZERO;
		if (ValidateUtil.isNotEmptyString(member.getTerminalIds())) {
			String[] strIds = member.getTerminalIds().split(",");
			List<String> list = Arrays.asList(strIds);
			Collection<Long> idCollection = new ArrayList<>();
			list.forEach(item -> {
				idCollection.add(Long.valueOf(item));
			});
			List<CentreTerminal> centreTerminalList = centreTerminalMapper.selectByIdIn(idCollection,member.getCentreId());
			if(ValidateUtil.isEmptyCollection(centreTerminalList)){
				centreTerminalList= centreTerminalMapper.selectByIdIn(idCollection,null);
			}
			if (centreTerminalList == null) {
				throw new BDException("终端配置错误，请联系管理员！");
			}
			for (CentreTerminal centreTerminal : centreTerminalList) {
				payPrice = payPrice.add(centreTerminal.getStoresPay());
			}
		}
		member.setPayPrice(payPrice);

		//本地生活门店推荐人   前端传递的参数为手机号   通过手机号和centreId查询对应用户  如果为王权会员（isVip = 1）   则将id设置
		if ((MemberStoresApplicationWayEnum.LOCAL_LIFE.getCode().equals(member.getStoresApplicationWay()) || MemberStoresApplicationWayEnum.SMALL_PROGRAM.getCode().equals(member.getStoresApplicationWay()))
				&& member.getReferrerMid() != null) {
			Member memberResult = memberMapper.getByMobileCenter(String.valueOf(member.getReferrerMid()), member.getCentreId());
			if (memberResult != null) {
				if (memberResult.getIsVip() == 1) {
					member.setReferrerMid(memberResult.getId());
				}else if(memberResult.getIsVip() == 0){
					throw new BDException("普通用户不能推荐门店入驻！");
				}
			} else {
				throw new BDException("没有号码为" + member.getReferrerMid() + "的用户！");
			}
			if(MemberStoresApplicationWayEnum.LOCAL_LIFE.getCode().equals(member.getStoresApplicationWay())){
				member.setIsLocalLifeStoreFlag(1); //是否本地生活门店 0-否，1-是
			}
			if(MemberStoresApplicationWayEnum.SMALL_PROGRAM.getCode().equals(member.getStoresApplicationWay())){
				member.setIsAppletsStoreFlag(1);//是否小程序门店 0-否，1-是
			}
		}


		//是否商户下直属门店(0不是1是)
		Integer isMerchantDirectStore = member.getIsMerchantDirectStore();
		if( isMerchantDirectStore != null && isMerchantDirectStore == 0 ){
			if( centre != null ){
				member.setAcqSpId(centre.getYplCustomerCode());
			}
			if( StringUtils.isEmpty(member.getMerchantName()) || StringUtils.isEmpty(member.getLawyerCertNo()) ||
					StringUtils.isEmpty(member.getContactPhone()) || StringUtils.isEmpty(member.getMerchantEmail()) ||
					StringUtils.isEmpty(member.getSettleAccountNo()) || StringUtils.isEmpty(member.getOpenBank())){
				throw new BDException("直属门店有信息不能为空");
			}
		}

		return memberMapper.updateByPrimaryKeySelective(member);
	}

	@Override
	public List<Member> getNewNearCommanders(Double longitude, Double latitude, String teamName,
											 Long centreId, Long mid, Integer flag, Integer terminalIds, int offset, int limit,
											 Integer isLocalLifeStoreFlag, Integer isAppletsStoreFlag,Long industryBrandId) throws ParseException {
		Map<String, Object> params = new HashMap<>(4);
		if (StringUtils.isNotEmpty(teamName)) {
			params.put("teamName", teamName);
		} else {
			params.put("longitude", longitude);
			params.put("latitude", latitude);
		}
		if (terminalIds != null) {
			params.put("terminalIds", terminalIds);
		}
		if (centreId != null) {
			params.put("centreId", centreId);
		}
		if (mid != null) {
			params.put("mid", mid);
		}
		if (flag != null) {
			params.put("flag", flag);
		}
		if (flag == null) {
			params.put("flag", 1);
		}
		if(isLocalLifeStoreFlag != null){
			params.put("isLocalLifeStoreFlag", isLocalLifeStoreFlag);
		}
		if(isAppletsStoreFlag != null){
			params.put("isAppletsStoreFlag", isAppletsStoreFlag);
		}
		if(industryBrandId != null){
			params.put("industryBrandId",industryBrandId);
		}
		Centre centre = centreService.getByKey(centreId);
		if (centre != null && ValidateUtil.isNotEmptyString(centre.getIndustryId())) {
			params.put("industryId", centre.getIndustryId());
		}
		List<Member> list = memberMapper.getNewNearCommanders(params, new RowBounds(offset, limit));

		if (CollectionUtils.isNotEmpty(list)) {
			double distributionScope = 5d;
			TradeConfig tradeConfig = configService.getTradeConfig(centreId);
			if (null != tradeConfig && tradeConfig.getDistributionScope() != null) {
				distributionScope = tradeConfig.getDistributionScope();
			}
			for (Member member : list) {
				member.setTicket(null);
				if (StringUtils.isNotEmpty(member.gettLat()) && StringUtils.isNotEmpty(member.gettLng()) && member.getDistance() != null) {
					Double distance = new BigDecimal(member.getDistance() / 1000).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue();
					member.setDistance(distance);
					if (distance > distributionScope) {//大于5公里，则为超出
						member.setStatus(100);//超出配送范围，默认临时设置100状态，不作其他的处理判断
					}
				} else {//超出配送范围，默认临时设置100状态，不作其他的处理判断
					member.setStatus(100);
				}
				//查询店铺时段
				Store store = storeService.getStoreByTeamid(member.getId());
				if (store == null) {
					member.setBusiStatus(1);//营业状态 1-营业中 2-休息中
				} else {
					member.setBusiStatus(2);
					if (store.getBusinessTimeList() != null && store.getBusinessTimeList().size() > 0) {
						//多时段营业时间判断
						SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						Date now = new Date();
						SimpleDateFormat ds = new SimpleDateFormat("yyyy-MM-dd ");
						for (BusinessTimeVo timeVo : store.getBusinessTimeList()) {
							Date beginTime = df.parse(ds.format(now) + timeVo.getBeginTime());
							Date endTime = df.parse(ds.format(now) + timeVo.getEndTime());
							//before  < 在..之前  after > 在..之后
							if (beginTime.before(now) && endTime.after(now)) {
								member.setBusiStatus(1);
								break;
							}
						}
					}else{
						member.setBusiStatus(1);
					}
				}

			}
		}
		//list.sort(Comparator.comparing(Member::getDistance, Comparator.nullsFirst(Comparator.naturalOrder())));
		return list;
	}

	@Override
	public int saveAccessLog(AccessLog log) {
		if (log == null || log.getMid() == null) {
			return 0;
		}
		return 0;
	}



	@Override
	public List<Member> getNearCommanders(double longitude, double latitude, String teamName,
										  Long centreId, Long mid, Integer flag, int offset, int limit) {
		Map<String, Object> params = new HashMap<>(4);
		if (StringUtils.isNotEmpty(teamName)) {
			params.put("teamName", teamName);
		} else {
			params.put("longitude", longitude);
			params.put("latitude", latitude);
		}
		if (centreId != null) {
			params.put("centreId", centreId);
		}
		if (mid != null) {
			params.put("mid", mid);
		}
		if (flag != null) {
			params.put("flag", flag);
		}
		if (flag == null) {
			params.put("flag", 1);
		}
		List<Member> list = memberMapper.getNearCommanders(params, new RowBounds(offset, limit));
		if (CollectionUtils.isNotEmpty(list)) {
			for (Member member : list) {
				member.setTicket(null);
				if (StringUtils.isNotEmpty(member.getLat()) && StringUtils.isNotEmpty(member.getLng())) {
					Double distance = LocationUtils.getDistance(Double.parseDouble(member.getLat()), Double.parseDouble(member.getLng()), latitude, longitude);
					member.setDistance(new BigDecimal(distance).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
				}
			}
		}
		list.sort(Comparator.comparing(Member::getDistance));
		return list;
	}

	@Override
	public Map<String, Object> getShopRankings(Long tmid, Integer timeType) {
		if (tmid == null) {
			return null;
		}
		Member tm = memberMapper.selectByPrimaryKey(tmid);
		if (tm == null) {
			return null;
		}

		Date start = null;
		Date end = null;
		int startH = 20, startM = 30, endH = 20, endM = 0;
		TradeConfig config = configService.getTradeConfig(tm.getCentreId());
		if (config != null) {
			startH = config.getNodeHour() == null ? startH : config.getNodeHour();
			startM = config.getNodeMin() == null ? startM : config.getNodeMin();
			endH = config.getFreeEndHour() == null ? endH : config.getFreeEndHour();
			endM = config.getFreeEndMin() == null ? endM : config.getFreeEndMin();
		}

		Map<String, Object> result = new HashMap<>(4);
		if (Objects.equals(timeType, TimeType.ALL.getCode())) {
			result.put("timeType", TimeType.ALL.getName());
		} else if (Objects.equals(timeType, TimeType.TODAY.getCode())) {
			result.put("timeType", TimeType.TODAY.getName());
			start = DateUtils.getAppointTime(DateUtils.getAddDayDate(new Date(), -1), startH, startM);
			end = DateUtils.getAppointTime(new Date(), endH, endM);


		} else if (Objects.equals(timeType, TimeType.WEEK.getCode())) {
			result.put("timeType", TimeType.WEEK.getName());
			start = DateUtils.getAppointTime(DateUtils.getWeekFirstDay(), startH, startM);
			end = DateUtils.getAppointTime(new Date(), endH, endM);

		} else {
			result.put("timeType", TimeType.MONTH.getName());
			start = DateUtils.getAppointTime(DateUtils.getAddDayDate(getMonthStart(), -1), startH, startM);
			end = DateUtils.getAppointTime(new Date(), endH, endM);

		}


		List<ShopRankingsInfo> list = orderProductMapper.getShopRankings(tm.getCentreId(), start, end);
		result.put("shopRankings", list);
		return result;
	}

	@Override
	public PageUtils<Member> listTeamMembers(Long tmid, String queryItem, int offset, int limit) {
		PageUtils<Member> pageUtils = new PageUtils<>();
		if (tmid == null) {
			return pageUtils;
		}

		int total = memberMapper.countTeamMembers(tmid, queryItem);
		if (total > 0) {
			pageUtils.setTotal(total);
			List<Member> list = memberMapper.listTeamMembers(tmid, queryItem, new RowBounds(offset, limit));
			for (Member m : list) {
				OrderProductExample ope = new OrderProductExample();
				OrderProductExample.Criteria criteria = ope.createCriteria();
				criteria.andTMidEqualTo(tmid)
						.andMidEqualTo(m.getId())
						.andStatusGreaterThanOrEqualTo(OrderStatus.wait_send.getCode());
				int orderTotal = orderProductMapper.countByExample(ope);
				m.setOrderSum(orderTotal);
				m.setContributeCommission(orderProductMapper.contributeCommission(m.getId(), tmid));
				m.setTicket(null);
			}
			pageUtils.setRows(list);
		}
		return pageUtils;
	}

	@Override
	public Member getByAppOpenId(String openId) {
		if (StringUtils.isEmpty(openId)) {
			return null;
		}
		Member member = memberMapper.getByAppOpenId(openId);
		if (member == null) {
			logger.info("not found member by openId:{}", openId);
			return null;
		}
		member.setTicket(null);
		return member;
	}

	@Override
	@CacheEvict(value = CACHE_NAME, allEntries = true)
	@Transactional(rollbackFor = Exception.class)
	public int buyVipWx(Long mid, String payNo, String invCode) {
		if (mid == null || StringUtils.isEmpty(payNo)) {
			return 0;
		}
		Member member = memberMapper.selectByPrimaryKey(mid);
		if (member == null) {
			logger.info("not found member info by id:{}", mid);
			return 0;
		}
		//vip商户数据集合
		List<String> strlist = Arrays.asList(member.getVipofcentreId().split("-"));
		if (member.getIsVip() == 1 && strlist.indexOf(member.getCentreId().toString()) != -1) {
			throw new BDException(BusinessCode.MEMBER_VIP_ALREADY);
		}
		TradeConfig tc = configService.getTradeConfig(member.getCentreId());
		if (tc == null || tc.getVipPrice() == null) {
			throw new BDException(BusinessCode.MEMBER_VIP_PRICE_ERROR);
		}
		member.setVipofcentreId(member.getVipofcentreId().concat(member.getCentreId() + "-"));
		member.setIsVip(1);
		member.setVipTime(new Date());

		Payment payment = new Payment();
		payment.setCreateTime(new Date());
		payment.setMid(mid);
		payment.setMoney(BigDecimal.valueOf(tc.getVipPrice()));
		payment.setPayTradeNo(payNo);
		payment.setStatus(2);
		payment.setType("2");
		payment.setStyle(3);
		payment.setOpenid(member.getOpenid());
		paymentMapper.insertSelective(payment);

		Long inviterId = null;
		if (inviterId == null) {
			//用户的推荐人
			inviterId = member.getUserid();
		}
		if (inviterId != null) {
			//会员有推荐人，推荐人返现奖励
			if (tc.getVipRewardRate() != null && tc.getVipRewardRate() > 0) {
				double reward = BigDecimal.valueOf(tc.getVipPrice() * tc.getVipRewardRate()).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				balanceService.recharge(inviterId, reward, BalanceLogStyle.REWARD_VIP.getCode(), RechargeType.VIP_REWARD.getType(), String.valueOf(mid));
			}
		}
		//站点余额账号
		CentreAmount ca = centreAmountMapper.getByKey(member.getCentreId());
		AmountLog al = new AmountLog();
		al.setCentreId(member.getCentreId());
		al.setBeforeamount(ca.getAmount());
		al.setMoney(new BigDecimal(tc.getVipPrice()));
		al.setAfteramount(ca.getAmount().add(new BigDecimal(tc.getVipPrice())));
		al.setCreateTime(new Date());
		al.setFlowType(13);
		al.setProductType(1);
		al.setRemark("会员购买vip");
		//站点流水记录
		amountLogMapper.saveAmountLog(al);
		centreAmountMapper.changeAmount(new CentreAmount(member.getCentreId(), BigDecimal.valueOf(tc.getVipPrice())));
		return memberMapper.updateByPrimaryKeySelective(member);
	}



	@Override
	public Member getTmByTeamSeqId(String teamSeqId) {
		MemberAggregation memberAggregation = memberAggregationMapper.queryByCode(teamSeqId);
		if (null == memberAggregation) {
			return null;
		}
		return memberMapper.selectByPrimaryKey(memberAggregation.getMid());
	}


	@Override
	public LocalLifeStoreVo getLocalStoreDetail(Long shopMemberId) {
		LocalLifeStoreVo storeVo = new LocalLifeStoreVo();
		Member shopMember = memberMapper.selectByPrimaryKey(shopMemberId);
		if (null == shopMember) {
			throw new BDException("门店信息异常");
		}
		storeVo.setStoreName(shopMember.gettXiaoqu());
		storeVo.setAddress(shopMember.gettProvince() + shopMember.gettCity() + shopMember.gettArea() + shopMember.gettAddress());
		storeVo.setThumb(shopMember.getStore());

		Store store = storeService.getStoreByTeamid(shopMemberId);
		if (null != store) {
			if (ValidateUtil.isNotEmptyCollection(store.getBusinessTimeList())) {
				StringBuilder stringBuilder = new StringBuilder();
				for (BusinessTimeVo timeVo : store.getBusinessTimeList()) {
					stringBuilder.append(timeVo.getBeginTime() + "-" + timeVo.getEndTime() + StringConstans.STR_SPACE);
				}
				storeVo.setBusinessBeginTime(stringBuilder.toString());
			}

			storeVo.setMobile(store.getPhone());
			storeVo.setFreechargeDesc(store.getFreechargeDesc());
			storeVo.setShopEnv(store.getShopEnv());
			storeVo.setDiscountRule(store.getDiscountRule());
			storeVo.setLat(store.getLatitude());
			storeVo.setLng(store.getLongitude());
			storeVo.setNotice(store.getNotice());
		}
		//计算店铺总价格
		storeVo.setTotalPrice(storeService.getStoreProductPrice(shopMemberId));

		return storeVo;
	}

	/**
	 * 获取用户发码权限信息
	 *
	 * @return
	 */
	@Override
	public Member getMemberCdkSendLimit(Long mid) {
		if (mid == null) {
			return null;
		}
		Member member = memberMapper.selectCdkSendLimitByPrimaryKey(mid);
		if (member == null) {
			return null;
		}
		return member;
	}


	@Override
	public List<Map<String, Object>> getCommanderProfitInfo(Long teamId, Date start, Date end) {
		Member tm = memberMapper.selectByPrimaryKey(teamId);
		if (tm == null) {
			return null;
		}
		int startH = 20, startM = 30, endH = 20, endM = 0;
		TradeConfig config = configService.getTradeConfig(tm.getCentreId());
		if (config != null) {
			startH = config.getNodeHour() == null ? startH : config.getNodeHour();
			startM = config.getNodeMin() == null ? startM : config.getNodeMin();
			endH = config.getFreeEndHour() == null ? endH : config.getFreeEndHour();
			endM = config.getFreeEndMin() == null ? endM : config.getFreeEndMin();
		}
		if (start == null) {
			start = DateUtils.getAppointTime(DateUtils.getAddDayDate(new Date(), -7), startH, startM);
			end = DateUtils.getAppointTime(new Date(), endH, endM);
		} else {
			start = DateUtils.getAppointTime(DateUtils.getAddDayDate(start, -1), startH, startM);
			end = DateUtils.getAppointTime(new Date(), endH, endM);
		}
		return orderProductMapper.getCommanderProfitInfo(teamId, start, end);
	}

	@Override
	public double getTodayExpectIncome(Long teamId) {
		if (teamId == null) {
			return 0d;
		}
		Member tm = memberMapper.selectByPrimaryKey(teamId);
		if (tm == null) {
			return 0d;
		}
		int startH = 20, startM = 30, endH = 20, endM = 0;
		TradeConfig config = configService.getTradeConfig(tm.getCentreId());
		if (config != null) {
			startH = config.getNodeHour() == null ? startH : config.getNodeHour();
			startM = config.getNodeMin() == null ? startM : config.getNodeMin();
			endH = config.getFreeEndHour() == null ? endH : config.getFreeEndHour();
			endM = config.getFreeEndMin() == null ? endM : config.getFreeEndMin();
		}
		Date start = DateUtils.getAppointTime(DateUtils.getAddDayDate(new Date(), -1), startH, startM);
		Date end = DateUtils.getAppointTime(new Date(), endH, endM);
		return orderProductMapper.getTeamExpectIncome(teamId, start, end);
	}


	@Override
	public PageUtils<Member> listTeamCommanders(Long tmid, String queryItem, int offset, int limit) {
		PageUtils<Member> pageUtils = new PageUtils<>();
		if (tmid == null) {
			return pageUtils;
		}
		Map<String, Object> params = new HashMap<>(2);
		params.put("tmid", tmid);
		if (StringUtils.isNotEmpty(queryItem)) {
			params.put("queryItem", queryItem);
		}
		int total = memberMapper.countTeamCommanders(params);
		if (total > 0) {
			List<Member> list = memberMapper.listTeamCommanders(params, new RowBounds(offset, limit));
			for (Member m : list) {
				m.setTicket(null);
				m.setCommissionTotal(commissionService.commissionCount(m.getId(), null));
				m.setWaitGrantCommission(commissionService.commissionCount(m.getId(), 0));
			}
			pageUtils.setTotal(total);
			pageUtils.setRows(list);
		}
		return pageUtils;
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(value = CACHE_NAME, allEntries = true)
	public int buyVipByBalanceCard(Long mid, String invCode, String level) {
		if (mid == null) {
			return 0;
		}

		Member member = memberMapper.selectByPrimaryKey(mid);
		if (member == null) {
			logger.info("not found member info by id:{}", mid);
			return 0;
		}
		//vip商户数据集合
		List<String> strlist = Arrays.asList(member.getVipofcentreId().split("-"));
		if (member.getIsVip() == 1 && strlist.indexOf(member.getCentreId().toString()) != -1) {
			throw new BDException(BusinessCode.MEMBER_VIP_ALREADY);
		}
		TradeConfig tc = configService.getTradeConfig(member.getCentreId());
		if (tc == null || tc.getVipPrice() == null) {
			throw new BDException(BusinessCode.MEMBER_VIP_PRICE_ERROR);
		}
		if (tc.getVipPrice() > member.getCredit2().doubleValue()) {
			logger.info("余额小于会员金额");
			return 0;
		}
		member.setVipofcentreId(member.getVipofcentreId().concat(member.getCentreId() + "-"));
		member.setIsVip(1);
		member.setVipTime(new Date());
		member.setCredit2(member.getCredit2().subtract(BigDecimal.valueOf(tc.getVipPrice())));
		balanceService.deduct(mid, tc.getVipPrice(), BalanceLogStyle.BUY_VIP2.getCode(), RechargeType.BUY_VIP.getType(), "会员购买vip", null, null);

		Long inviterId = null;
		if (inviterId == null) {
			//用户的推荐人
			inviterId = member.getUserid();
		}
		if (inviterId != null) {
			//会员有推荐人，推荐人返现奖励
			if (tc.getVipRewardRate() != null && tc.getVipRewardRate() > 0) {
				double reward = BigDecimal.valueOf(tc.getVipPrice() * tc.getVipRewardRate()).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				balanceService.recharge(null, reward, BalanceLogStyle.REWARD_VIP.getCode(), RechargeType.VIP_REWARD.getType(), String.valueOf(mid));
			}
		}
		//站点余额账号
		CentreAmount ca = centreAmountMapper.getByKey(member.getCentreId());
		AmountLog al = new AmountLog();
		al.setCentreId(member.getCentreId());
		al.setBeforeamount(ca.getAmount());
		al.setMoney(new BigDecimal(tc.getVipPrice()));
		al.setAfteramount(ca.getAmount().add(new BigDecimal(tc.getVipPrice())));
		al.setCreateTime(new Date());
		al.setFlowType(13);
		al.setProductType(1);
		al.setRemark("会员购买vip");

		//电子名片的分佣逻辑
		if (StringUtils.isNotBlank(level)) {
			if ("188".equals(level)) {
				if (member.getGender() == 1) {//只有是普通会员才去升级
					member.setGender(2);
				}
			}

			Long refId = member.getUserid();
			if (refId != null) {
				Member refMem = memberMapper.selectByPrimaryKey(refId);
				if (refMem != null) {
					int grade = refMem.getGrade();
					if (grade >= 3) {//普通会员和vip不参与分佣
						BrokerageVo brokerage = tBusinessCardService.getBrokerageById((long) grade);
						BigDecimal commission1 = BigDecimal.ZERO; //直推佣金
						BigDecimal commission2 = BigDecimal.ZERO; //团队佣金
						if ("188".equals(level)) {
							commission1 = brokerage.getBrokerage1();
							commission2 = brokerage.getBrokerage2();
						}
						//如果买的是888电子名片
						if ("888".equals(level)) {
							commission1 = brokerage.getBrokerage3();
							commission2 = brokerage.getBrokerage4();
						}

						//设置会员金额
						member.setCredit2(member.getCredit2().add(commission1).add(commission2));
						//推荐佣金记录
						CommissionLog log1 = new CommissionLog();
						log1.setMid(refId);
						log1.setType(1);
						log1.setCommission(commission1);
						log1.setIsGrant(1);
						log1.setGrantTime(new Date());
						//团队佣金记录
						CommissionLog log2 = new CommissionLog();
						log1.setMid(refId);
						log1.setType(2);
						log1.setCommission(commission2);
						log1.setIsGrant(1);
						log1.setGrantTime(new Date());
						//保存数据
						tBusinessCardMapper.insertCommission(log1);
						tBusinessCardMapper.insertCommission(log2);
					}
				}
			}


		}


		//站点流水记录
		amountLogMapper.saveAmountLog(al);
		//给站点充值
		centreAmountMapper.changeAmount(new CentreAmount(member.getCentreId(), BigDecimal.valueOf(tc.getVipPrice())));
		return memberMapper.updateByPrimaryKeySelective(member);
	}

	@Override
	public Member getByOpenId(String openId) {
		if (StringUtils.isEmpty(openId)) {
			return null;
		}
		Member member = memberMapper.getByOpenId(openId);
		if (member == null) {
			logger.info("not found member by openId:{}", openId);
			return null;
		}
		member.setTicket(null);
		return member;
	}


	@Override
	public Member getByUnionId(String unionId) {
		return memberMapper.getByUnionId(unionId);
	}

	@Override
	public long saveMember(Member member) {
		if (member == null) {
			return 0;
		}
		member.setMyCode(CommonUtils.generateRandomStr(8));
		if (member.getOpenid()!=null){
			Fans fans = fansMapper.getByOpenId(member.getOpenid());
			if (fans == null) {
				fans = new Fans();
				fans.setOpenid(member.getOpenid());
				fans.setNickname(member.getNickname());
				if (member.getFollow() != null && member.getFollow() == 1) {
					fans.setFollow(1);
					fans.setFollowtime(new Date());
				} else {
					fans.setFollow(2);
				}
				/**添加是否关注记录**/
				fansMapper.insertSelective(fans);
			} else {
				if (member.getFollow() != null && member.getFollow() == 1) {
					fans.setFollow(1);
					fans.setFollowtime(new Date());
				} else {
					fans.setFollow(2);
				}
				fansMapper.updateByPrimaryKeySelective(fans);
			}
		}

		memberMapper.insertSelective(member);
		/**添加积分记录，初始为0**/
        /*Integral integral = new Integral();
        integral.setMid(member.getId());
        integralMapper.insertSelective(integral);*/
		return member.getId();
	}

	@Override
	public int updateByPrimaryKeySelective(Member record) {
		return memberMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	@CachePut(value = CACHE_TICKET_NAME, key = "#mid")
	public String setTicket(Long mid, String ticket) {
		if (mid == null || StringUtils.isEmpty(ticket)) {
			return null;
		}
		Member member = new Member();
		member.setId(mid);
		member.setTicket(ticket);
		memberMapper.updateByPrimaryKeySelective(member);
		return ticket;
	}

	@Override
	public List<Member> getMemByUserId(Map params) {
		return memberMapper.getMemberByReferrals(params);
	}

	@Override
	@CacheEvict(value = CACHE_NAME, allEntries = true)
	@Transactional(rollbackFor = Exception.class)
	public int buyVipWxCard(Long mid, String payNo, String invCode, String level) {
		if (mid == null || StringUtils.isEmpty(payNo)) {
			return 0;
		}
		Member member = memberMapper.selectByPrimaryKey(mid);
		if (member == null) {
			logger.info("not found member info by id:{}", mid);
			return 0;
		}
		//vip商户数据集合
		List<String> strlist = Arrays.asList(member.getVipofcentreId().split("-"));
//        if (member.getIsVip() == 1 && strlist.indexOf(member.getCentreId().toString()) != -1) {
//            throw new BDException(BusinessCode.MEMBER_VIP_ALREADY);
//        }
		TradeConfig tc = configService.getTradeConfig(member.getCentreId());
		if (tc == null || tc.getVipPrice() == null) {
			throw new BDException(BusinessCode.MEMBER_VIP_PRICE_ERROR);
		}
		member.setVipofcentreId(member.getVipofcentreId().concat(member.getCentreId() + "-"));
//        member.setIsVip(1);
		member.setVipTime(new Date());

		Payment payment = new Payment();
		payment.setCreateTime(new Date());
		payment.setMid(mid);
		payment.setMoney(BigDecimal.valueOf(tc.getVipPrice()));
		payment.setPayTradeNo(payNo);
		payment.setStatus(2);
		payment.setType("2");
		payment.setStyle(3);
		payment.setOpenid(member.getOpenid());
		paymentMapper.insertSelective(payment);

		Long inviterId = null;
		if (inviterId == null) {
			//用户的推荐人
			inviterId = member.getUserid();
		}
		if (inviterId != null) {
			//会员有推荐人，推荐人返现奖励
			if (tc.getVipRewardRate() != null && tc.getVipRewardRate() > 0) {
				double reward = BigDecimal.valueOf(tc.getVipPrice() * tc.getVipRewardRate()).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				balanceService.recharge(null, reward, BalanceLogStyle.REWARD_VIP.getCode(), RechargeType.VIP_REWARD.getType(), String.valueOf(mid));
			}
		}
		//站点余额账号
		CentreAmount ca = centreAmountMapper.getByKey(member.getCentreId());
		AmountLog al = new AmountLog();
		al.setCentreId(member.getCentreId());
		al.setBeforeamount(ca.getAmount());
		al.setMoney(new BigDecimal(tc.getVipPrice()));
		al.setAfteramount(ca.getAmount().add(new BigDecimal(tc.getVipPrice())));
		al.setCreateTime(new Date());
		al.setFlowType(13);
		al.setProductType(1);
		al.setRemark("会员购买vip");

		//电子名片的分佣逻辑

		if (StringUtils.isNotBlank(level)) {
			System.out.println("------------- level:" + level);
			if ("188".equals(level)) {
				if (member.getGrade() == 1) {//只有是普通会员才去升级
					member.setGrade(2);
					memberMapper.updateByPrimaryKeySelective(member);
				}
			}

			Long refId = member.getUserid();
			if (refId != null) {
				Member refMem = memberMapper.selectByPrimaryKey(refId);
				//获取推荐人推荐用户的个数
				Member tjrMem = refMem;
				while (tjrMem != null) {
					int grade = tjrMem.getGrade();
					int count = getCountByMemberByMidBuy(tjrMem.getId());
					//VI的级别配置
					BrokerageVo brokerageVov1 = tBusinessCardService.getBrokerageById(3L);
					if (count >= brokerageVov1.getCount().intValue()) {
						tjrMem.setGrade(brokerageVov1.getId().intValue());
					}
					BrokerageVo brokerageVov2 = tBusinessCardService.getBrokerageById(4L);
					if (count >= brokerageVov2.getCount().intValue()) {
						tjrMem.setGrade(brokerageVov2.getId().intValue());
					}
					BrokerageVo brokerageVov3 = tBusinessCardService.getBrokerageById(5L);
					if (count >= brokerageVov3.getCount().intValue()) {
						tjrMem.setGrade(brokerageVov3.getId().intValue());
					}

					if (tjrMem.getGrade() > grade) {//如果是升级了才会去改变用户会员等级
						memberMapper.updateByPrimaryKey(tjrMem);
					}

					tjrMem = getByKey(tjrMem.getUserid());
				}

				if (refMem != null && refMem.getGrade() >= 2) {
					int grade = refMem.getGrade();
					BrokerageVo brokerage = tBusinessCardService.getBrokerageById((long) grade);

					BigDecimal commission1 = BigDecimal.ZERO; //直推佣金
					BigDecimal commission2 = BigDecimal.ZERO; //团队佣金
					if ("188".equals(level)) {
						commission1 = brokerage.getBrokerage1();
						if (grade > 2) {//团队佣金
							commission2 = brokerage.getBrokerage2();
						}
					}

					//设置会员推荐佣金=直推佣金+团队佣金
					refMem.setCredit2(refMem.getCredit2().add(commission1).add(commission2));
					//推荐佣金记录
					CommissionLog log1 = new CommissionLog();
					log1.setMid(refId);
					log1.setType(1);
					log1.setCommission(commission1);
					log1.setIsGrant(1);
					//保存数据
					tBusinessCardMapper.insertCommission(log1);
					if (grade > 2) {//团队佣金必须是v1或者以上
						//团队佣金记录
						CommissionLog log2 = new CommissionLog();
						log2.setMid(refId);
						log2.setType(2);
						log2.setCommission(commission2);
						log2.setIsGrant(1);
						tBusinessCardMapper.insertCommission(log2);
					}
					memberMapper.updateByPrimaryKeySelective(refMem);

					//团队管理佣金
					int gradeNow = refMem.getGrade();
					//二级推荐人佣金
					Member member1 = memberMapper.selectByPrimaryKey(refMem.getUserid());
					while (member1 != null) {
						if (member1 != null) {
							int memGrade = member1.getGrade();
							if (memGrade > gradeNow && memGrade > 2) {
								gradeNow = memGrade;
								BrokerageVo brokerage1 = tBusinessCardService.getBrokerageById((long) gradeNow);
								BigDecimal commission3 = brokerage1.getBrokerage2();
								CommissionLog log3 = new CommissionLog();
								log3.setMid(member1.getId());
								log3.setType(2);
								log3.setCommission(commission3);
								log3.setIsGrant(1);
								tBusinessCardMapper.insertCommission(log3);
								member1.setCredit2(member1.getCredit2().add(commission3));
								memberMapper.updateByPrimaryKeySelective(member1);

								member1 = memberMapper.selectByPrimaryKey(member1.getUserid());
							} else {
								member1 = memberMapper.selectByPrimaryKey(member1.getUserid());
							}
						} else {
							break;
						}
					}

				}
			}

		}

		//站点流水记录
		amountLogMapper.saveAmountLog(al);
		centreAmountMapper.changeAmount(new CentreAmount(member.getCentreId(), BigDecimal.valueOf(tc.getVipPrice())));
		return memberMapper.updateByPrimaryKeySelective(member);
	}

	@Override
	@CacheEvict(value = CACHE_NAME, allEntries = true)
	@Transactional(rollbackFor = Exception.class)
	public int buyLifeVipWx(Long mid, String payNo, String invCode, Integer vipType) {
		if (mid == null || StringUtils.isEmpty(payNo)) {
			return 0;
		}
		Member member = memberMapper.selectByPrimaryKey(mid);
		if (member == null) {
			logger.info("not found member info by id:{}", mid);
			return 0;
		}
		//vip商户数据集合
		List<String> strlist = Arrays.asList(member.getVipofcentreId().split("-"));
		if (member.getIsVip() == 1 && strlist.indexOf(member.getCentreId().toString()) != -1) {
			throw new BDException(BusinessCode.MEMBER_VIP_ALREADY);
		}
		LifeConfig tc = configService.getLifeConfig(member.getCentreId());
		String vipPrice;
		//type 0季度   1年
		if (vipType != null && vipType == 0) {
			vipPrice = tc.getKingshipVipQuarter();
		} else {
			vipPrice = tc.getKingshipVipYear();
		}

		if (tc == null || vipPrice == null) {
			throw new BDException(BusinessCode.MEMBER_VIP_PRICE_ERROR);
		}
		member.setVipofcentreId(member.getVipofcentreId().concat(member.getCentreId() + "-"));
		member.setIsVip(1);
		member.setVipTime(new Date());

		Payment payment = new Payment();
		payment.setCreateTime(new Date());
		payment.setMid(mid);
		payment.setMoney(new BigDecimal(vipPrice));
		payment.setPayTradeNo(payNo);
		payment.setStatus(2);
		payment.setType("2");
		payment.setStyle(3);
		payment.setOpenid(member.getOpenid());
		paymentMapper.insertSelective(payment);

		Long inviterId = null;
		if (inviterId == null) {
			//用户的推荐人
			inviterId = member.getUserid();
		}
		if (null != inviterId && ValidateUtil.isNotEmptyString(vipPrice) && !StringConstans.STR_ZERO.equals(vipPrice)) {
			BigDecimal kingshipVipPrice = new BigDecimal(vipPrice);
			//会员有1级推荐人，推荐人返现奖励
			if (ValidateUtil.isNotEmptyString(tc.getKingshipCommission1()) && !StringConstans.STR_ZERO.equals(tc.getKingshipCommission1())) {
				BigDecimal kingshipCommission1 = new BigDecimal(tc.getKingshipCommission1());
				double reward = kingshipVipPrice.multiply(kingshipCommission1).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				balanceService.recharge(inviterId, reward, BalanceLogStyle.LIFE_VIP.getCode(), RechargeType.LIFE_VIP_REWARD.getType(), String.valueOf(mid));
			}

			//会员有2级推荐人，推荐人返现奖励
			if (null != member.getUpUserid() && ValidateUtil.isNotEmptyString(tc.getKingshipCommission1()) && !StringConstans.STR_ZERO.equals(tc.getKingshipCommission1())) {
				BigDecimal kingshipCommission2 = new BigDecimal(tc.getKingshipCommission2());
				double reward = kingshipVipPrice.multiply(kingshipCommission2).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP).doubleValue();
				balanceService.recharge(inviterId, reward, BalanceLogStyle.LIFE_VIP.getCode(), RechargeType.LIFE_VIP_REWARD.getType(), String.valueOf(mid));
			}
		}

        /*
        数据示例
        王权会员支付单号：4200000917202012182964047081
        支付时间：2020-12-18 23:57:53
        支付金额：0.01
         */

		//新方法，启用微信模板的通知
		if (ValidateUtil.isNotEmptyString(member.getOpenid())) {

			/*
            {{first.DATA}}
            会员名称:{{keyword1.DATA}}
            会员账号:{{keyword2.DATA}}
            支付金额:{{keyword3.DATA}}
            到期时间:{{keyword4.DATA}}
            {{remark.DATA}}
             */
			logger.info("本地生活会员权益升级模版消息发送------------------");
			Map<String, String> map = new HashMap<>();
			String firstString = "恭喜您已成功升级王权会员！";
			String url = templatemsgCreateUserUrl+"/bdsh/"+member.getCentreId()+"/user/upgrade-admin-list/0";
			String productName = "王权会员";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Calendar cld = Calendar.getInstance();
			cld.add(Calendar.MONTH, 3);
			String Time_Now = sdf.format(cld.getTime());

			map.put("firstString",firstString);
			map.put("productName",productName);
			map.put("orderCount",member.getNickname() + StringConstans.STR_EMPTY);
			map.put("payprice",vipPrice + StringConstans.STR_EMPTY);
			map.put("endtime", Time_Now);
			map.put("remarkrest","支付单号:" + payNo);
			orderService.sendGZHOpenMembership(member.getCentreId(),member.getId(),map,url);
		}
		//发送文本通知
		if (ValidateUtil.isNotEmptyString(member.getOpenid())) {
			logger.info("本地生活会员权益升级文本消息发送------------------");
			WxNotifyParam notifyParam = new WxNotifyParam();
			notifyParam.setMessageType(WxMessageType.MESSAGE_TYPE_TEXT.getType());//文本消息
			notifyParam.setCenterId(member.getCentreId());
			notifyParam.setGzhOpenId(member.getOpenid());
			notifyParam.setTeminal(WxTerminal.TERMINAL_GZH.getTerminal());
			String content = "会员升级成功，您的权益如下：" + "\n";
			content += "1.获得购买门店大礼包及商品获得VIP补贴价，可以享受众多商户的海量优品补贴" + ";\n";
			content += "2.分享商品给好友购买，享受丰厚的分佣" + ";\n";
			content += "3.获得低门槛实现互联网轻创业的珍贵机会" + ";\n";
			content += "4.获得分享一个创客：90元" + ";\n";
			content += "5.获得分享一个门店：300元" + ";\n";
			content += "6.获得线下《琰掌柜互联网轻创密训营》2天，价值3800元" + ";\n";
			content += "7.获得1000好物兑换金币" + ";\n";
			content += "8.分享10个创客，可以获得门店经营权一个" + ";\n";
			notifyParam.setContent(content);
			wxNotifyService.sendNotify(notifyParam);
		}

		return memberMapper.updateByPrimaryKeySelective(member);
	}

	@Override
	public Long getCenterIdByShopMemberId(Long centerId) {
		return memberMapper.getCenterIdByShopMemberId(centerId);
	}

	@Override
	public Long getShopMemberIdByCenterId(Long shopMemberId) {
		return memberMapper.getShopMemberIdByCenterId(shopMemberId);
	}

	@Override
	public Member getOneByCentreIdAndMobile(Long centreId, String loginMobile) {
		return memberMapper.getOneByCentreIdAndMobile(centreId, loginMobile);
	}

}
